﻿using System;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Data;
using System.Collections.Generic;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Web;

public partial class Controls_RefundPays : System.Web.UI.UserControl
{
    int mLoanID = 0;
    int mIterationID = 0;
    int mPayID = 0;
    int mCurrencyID = 0;
    decimal mCurrencyChangeRate = 0;
    decimal mCurrenty = 0;

    public int LoanID
    {
        set { mLoanID = value; }
    }

    public int IterationID
    {
        set { mIterationID = value; }
    }

    public int PayID
    {
        set { mPayID = value; }
    }

    public int CurrencyID
    {
        set { mCurrencyID = value; }
    }

    public decimal CurrencyChangeRate
    {
        set { mCurrencyChangeRate = value; }
    }

    public decimal Currenty
    {
        set { mCurrenty = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        refundDateCalendarExtender.Format = Constants.Constants.ISODateBackwardDotsFormat;
        if (!IsPostBack)
        {
                    
        }
    }
    
    protected void ClearPersonalDataForms()
    {
        infoBoxTitleLabel.Text = string.Empty;

        refundDateTextBox.Text = string.Empty;
        refundPenaltyTextBox.Text = string.Empty;
        refundProfitTextBox.Text = string.Empty;
        refundMainTextBox.Text = string.Empty;
        refundTotalToPayTextBox.Text = string.Empty;
        refundDifferenceTextBox.Text = string.Empty;
        refundInputPaysTextBox.Text = string.Empty;

        refundCursCurentLabel.Text = string.Empty;
        refundCursFirstLabel.Text = string.Empty;
        refundCursMixtTextBox.Text = string.Empty;
    }

    public void Show()
    {
        string appPath = Utils.GetApplicationPath(Request);
        ClearPersonalDataForms();
        
        if (mLoanID != 0)
        {
            DataTable loanOrders = Utils.ModuleCredits().GetRefundsLoanOrderList(mLoanID);

            if (loanOrders != null && loanOrders.Rows.Count>0)
            {
                loanHiddenField.Value = mLoanID.ToString();
                iterationHiddenField.Value = mIterationID.ToString();
                payHiddenField.Value = mPayID.ToString();

                infoBoxTitleLabel.Text = "Refund iteration : " + mIterationID.ToString();
                DataRow[] selectedRows = loanOrders.Select("iterationID = " + mIterationID);
                decimal inputPays = 0;
                decimal penaltyPays = 0;
                decimal profitPays = 0;
                decimal mainPays = 0;
                decimal diffPays = 0;
                decimal mainBasic = 0;
                decimal profitBasic = 0;
                //decimal avansBasic = 0;
                DateTime startDate = new DateTime();

                for (int i = 0; i < selectedRows.Length; i++)
                {
                    string pays = selectedRows[i][8].ToString();
                    int paysID = 0;
                    int.TryParse(pays, out paysID);
                    
                    if (paysID == 0)
                    {
                        DateTime refundDate = DateTime.Parse(selectedRows[i][2].ToString());
                        refundDateLabel.Text = refundDate.ToString(Constants.Constants.ISODateBackwardDotsFormat);
                        startDate = DateTime.Parse(selectedRows[i][2].ToString());
                        
                        decimal.TryParse(selectedRows[i][3].ToString(), out mainBasic);
                        decimal.TryParse(selectedRows[i][4].ToString(), out profitBasic);
                        refundMainLabel.Text = selectedRows[i][3].ToString();
                        refundProfitLabel.Text = selectedRows[i][4].ToString();
                        refundTotaltoPayLabel.Text = (mainBasic+profitBasic).ToString();    //
                    }
                    else
                    {
                        string mainValue = selectedRows[i][3].ToString();
                        string profitValue = selectedRows[i][4].ToString();
                        string penaltyValue = selectedRows[i][5].ToString();
                        string avansValue = selectedRows[i][9].ToString();

                        decimal main = 0;
                        decimal profit = 0;
                        decimal penalty = 0;
                        decimal avans = 0;
                        decimal.TryParse(mainValue, out main);
                        decimal.TryParse(profitValue, out profit);
                        decimal.TryParse(penaltyValue, out penalty);
                        decimal.TryParse(avansValue, out avans);

                        if (mPayID != paysID)
                        {
                            mainPays += main;
                            profitPays += profit;
                            penaltyPays += penalty;
                            inputPays += main + profit + penalty;// +avans;
                        }

                        if (mPayID == paysID)
                        {
                            //Math.Round(penaltyAmount, 2).ToString();
                            DateTime refundDate = DateTime.Parse(selectedRows[i][2].ToString());
                            refundDateTextBox.Text = refundDate.ToString(Constants.Constants.ISODateBackwardDotsFormat);
                            refundInputPaysTextBox.Text = Math.Round((main + profit + penalty+avans),2).ToString();
                            refundPenaltyTextBox.Text = Math.Round(penalty, 2).ToString();
                            refundProfitTextBox.Text = Math.Round(profit,2).ToString();
                            refundMainTextBox.Text = Math.Round(main, 2).ToString();
                            refundTotalToPayTextBox.Text = refundInputPaysTextBox.Text;
                            refundDifferenceTextBox.Text = Math.Round(avans, 2).ToString();
                        }
                    }
                }

                DateTime curentDate = new DateTime();
                if (mPayID == 0)
                {
                    curentDate = DateTime.Now;
                    refundDateTextBox.Text = curentDate.ToString(Constants.Constants.ISODateBackwardDotsFormat);
                }
                else
                {
                    curentDate = Convert.ToDateTime(refundDateTextBox.Text);
                }

                refundInputPaysLabel.Text = inputPays.ToString();
                refundMainPaysLabel.Text = mainPays.ToString();
                refundProfitPaysLabel.Text = profitPays.ToString();
                refundPenaltyLabel.Text = penaltyPays.ToString();
                refundTotalPaysLabel.Text = inputPays.ToString();
                diffPays = (mainBasic + profitBasic) - (inputPays);
                refundDifferenceLabel.Text = diffPays.ToString();

                #region Intirziere
                
                DateTime firstDate = DateTime.Parse(refundDateLabel.Text);
                double difDate = (curentDate - firstDate).TotalDays;
                refundDaysDifferentLabel.Text = (Convert.ToInt32(difDate)).ToString();

                #endregion

                #region Penalitate
                if (mPayID == 0)
                {
                    Credits.DataObjects.LoanObject loanInfo = Utils.ModuleCredits().GetLoanObjectByID(mLoanID);
                    decimal penaltyValueFrom = loanInfo.ContractPenalty;
                    int calculatePenaltyFrom = loanInfo.CalculatePenaltyFrom;
                    decimal currencyRate = 1;
                    decimal initialAmount = loanInfo.ContractAmount;

                    decimal penaltyAmount = 0;

                    int delayDaysCount = Convert.ToInt32(difDate);

                    switch (calculatePenaltyFrom)
                    {
                        case (int)Constants.Constants.Classifiers.CalculatePenalty_DeLaSumaIntirzierii:
                            {
                                penaltyAmount = ((mainBasic + profitBasic) * penaltyValueFrom * currencyRate) / 100 * delayDaysCount;
                            }
                            break;

                        case (int)Constants.Constants.Classifiers.CalculatePenalty_DinSumaInitiala:
                            {
                                penaltyAmount = (initialAmount * penaltyValueFrom * currencyRate) / 100 * delayDaysCount;
                            }
                            break;

                        case (int)Constants.Constants.Classifiers.CalculatePenalty_SumaFixa:
                            {
                                penaltyAmount = penaltyValueFrom * delayDaysCount;
                            }
                            break;

                        default:
                            break;
                    }

                    if (penaltyAmount < 0)
                    {
                        penaltyAmount = 0;
                    }

                    refundPenaltyTextBox.Text = Math.Round(penaltyAmount, 2).ToString();
                    penaltyHiddenField.Value = penaltyValueFrom.ToString();
                }
                #endregion

                #region currencyChange
                                
                int currencyID = mCurrencyID;
                if (currencyID != 0 && currencyID != (int)Constants.Constants.CurrencyList.MDL)
                {
                    decimal realChangeRate = Utils.ModuleCredits().GetCurrencyRateByDate(DateTime.Now.Date, currencyID);
                    decimal startChangeRate = Utils.ModuleCredits().GetCurrencyRateByDate(startDate, currencyID);

                    refundCursFirstLabel.Text = startChangeRate.ToString();
                    refundCursCurentLabel.Text = realChangeRate.ToString();
                    refundCursMixtTextBox.Text = mCurrenty.ToString(); // startChangeRate > realChangeRate ? startChangeRate.ToString() : realChangeRate.ToString();
                    
                    if (mCurrencyChangeRate == 0)
                    {
                        mCurrencyChangeRate = 1;
                    }
                    
                    decimal inputCurs = (mainBasic + profitBasic) / mCurrencyChangeRate;

                    refundInputCursForingLabel.Text = (Math.Round(inputCurs, 2)).ToString();
                    refundInputValutaLabel.Text = (currencyID == 2 ? " USD" : " EURO");
                    refundInputPaysTextBox.Text = (mainBasic + profitBasic).ToString();
                    refundDifferenceToPayLabel.Text = "0";
                }
                else
                {
                    refundCursFirstLabel.Text = "1";
                    refundCursCurentLabel.Text = "1";
                    refundCursMixtTextBox.Text = mCurrenty.ToString();
                    refundInputCursForingLabel.Text = (mainBasic + profitBasic).ToString();
                    refundInputValutaLabel.Text = "MDL";
                }
                #endregion currencyChange
            }
        }
        
        this.programmaticModalPopup.Show();
    }
    
    protected void saveButton_Click(object sender, EventArgs e)
    {
        TextBox dateTextBox = (TextBox)this.FindControl("refundDateTextBox");
        DateTime payDate = Convert.ToDateTime(dateTextBox.Text);
        
        decimal main = 0;
        TextBox mainTextBox = (TextBox)this.FindControl("refundMainTextBox");
        decimal.TryParse(mainTextBox.Text.Replace('.',','), out main);

        decimal profit = 0;
        TextBox profitTextBox = (TextBox)this.FindControl("refundProfitTextBox");
        decimal.TryParse(profitTextBox.Text.Replace('.', ','), out profit);

        decimal penalty = 0;
        TextBox penaltyTextBox = (TextBox)this.FindControl("refundPenaltyTextBox");
        decimal.TryParse(penaltyTextBox.Text.Replace('.', ','), out penalty);
        
        decimal currenty = 1;
        TextBox currentyTextBox = (TextBox)this.FindControl("refundCursMixtTextBox");
        decimal.TryParse(currentyTextBox.Text.Replace('.', ','), out currenty);
        if (currenty <= 0)
        {
            currenty = 1;
        }

        decimal commission = 0;

        int loanValue = 0;
        HiddenField loanHiddenValue = (HiddenField)this.FindControl("loanHiddenField");
        int.TryParse(loanHiddenValue.Value, out loanValue);

        int iteration = 0;
        HiddenField iterationHidde = (HiddenField)this.FindControl("iterationHiddenField");
        int.TryParse(iterationHiddenField.Value, out iteration);

        int payID = 0;
        HiddenField payValue = (HiddenField)this.FindControl("payHiddenField");
        int.TryParse(payHiddenField.Value, out payID);

        decimal inputValue = 0;
        TextBox inputTextBox = (TextBox)this.FindControl("refundInputPaysTextBox");
        decimal.TryParse(inputTextBox.Text.Replace('.', ','), out inputValue);
        
        TextBox avansTextBox = (TextBox)this.FindControl("refundDifferenceTextBox");
        decimal avansValue = 0;
        decimal.TryParse(avansTextBox.Text.Replace('.', ','), out avansValue);
        
        int newPayID = 0;

        if (payID == 0)
        {
            bool isPenalty = false;
            if (penalty != 0)
            {
                isPenalty = true;
            }

            //bool result = Utils.ModuleCredits().AddNewRefund(loanValue, iteration, payDate
            //    , main, profit, penalty, currenty, commission, avansValue, 0, 0, isPenalty, 0, out newPayID);
        }
        else
        {
            if (inputValue == 0)
            {
                //delecte
                bool resultDelete = Utils.ModuleCredits().DeleteRefundByPayID(payID);
            }
            else
            {
                //update
                //bool resultUpdate = Utils.ModuleCredits().UpdateRefundByPayID(payID, payDate, main, profit, penalty, currenty, commission, avansValue);
                newPayID = payID;
            }
        }

        bool resultFinishedTranche = Utils.ModuleCredits().UpdateFinishedTranche(loanValue, iteration);
        
        if (avansValue > 0)
        {
            //bool resultAvans = Utils.ModuleCredits().AddAvansRefund(loanValue, iteration, payDate, avansValue, newPayID);
        }

        RefundsWindowEventsArg args = new RefundsWindowEventsArg(true);
        EntrySelected(this, args);
        
    }

    protected void cancelButton_Click(object sender, EventArgs e)
    {
        RefundsWindowEventsArg args = new RefundsWindowEventsArg(true);
        EntrySelected(this, args);
    }

    public class RefundsWindowEventsArg : EventArgs
    {
        private bool resultRefund;
        public bool ResultRefund
        {
            get { return resultRefund; }
        }

        public RefundsWindowEventsArg(bool result)
        {
            resultRefund = result;
        }
    }

    public event CustomItemEventHandler EntrySelected;
    public delegate void CustomItemEventHandler(object sender, Controls_RefundPays.RefundsWindowEventsArg e);
}